<?php

/*
 * This file is part of the yuki package.
 * Copyright (c) 2011 olamedia <olamedia@gmail.com>
 *
 * This source code is release under the MIT License.
 * 
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * yProfiler
 *
 * @package yuki
 * @subpackage profiler
 * @version SVN: $Id: yProfiler.php 109 2011-02-19 08:11:02Z olamedia@gmail.com $
 * @revision SVN: $Revision: 109 $
 * @date $Date: 2011-02-19 08:11:02 +0000 (Sat, 19 Feb 2011) $
 * @author olamedia
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 */
class yProfiler{
    /**
     * Tick time to register in benchmark log.
     */
    const LONG_TIME = 0.001;
    const TICK = 1;
    /**
     * Singleton instance.
     * @var yProfiler 
     */
    protected static $_instance = null;
    protected static $lastTickTime = null;
    protected $_benchmarkLog = array();
    /**
     * Get yProfiler instance.
     * @return yProfiler
     */
    public static function getInstance(){
        if (self::$_instance === null){
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    public function shutdown(){
        
    }
    /**
     * Starts profiler instance.
     * Register profiler handlers.
     */
    public static function start(){
        $profiler = self::getInstance();
        register_shutdown_function(array($profiler, 'shutdown'));
        register_tick_function(array($profiler, 'tickHandler'));


        declare(ticks=1); // will make first call to tickHandler
    }
    public function log($message, &$trace){
        $call = $trace[0];
        $this->_log[] = array($message, $trace);
        //$f = $call['file']; // called from this file
        //$l = $call['line']; // called at this line
    }
    /**
     * Tick handler.
     * Make use of declare(ticks=1); to log execution time.
     */
    public function tickHandler(){
        $time = microtime(true);
        if (self::$lastTickTime === null){
            self::$lastTickTime = $time;
        }
        $dt = $time - self::$lastTickTime;
        if ($dt > yProfiler::LONG_TIME){ // FIXME
            $trace = debug_backtrace();
            $this->_benchmarkLog[] = array($dt, $trace);
        }
        // connection_aborted()
        // memory_get_usage()
        //
        self::$lastTickTime = microtime(true);
    }
    /**
     * @magic
     * @return string 
     */
    public function __toString(){
        $s = '';
        foreach ($this->_benchmarkLog as $log){
            $s .= number_format($log[0], 6, '.', '')." at ".$log[1][0]['file'].":".$log[1][0]['line']." \n";
        }
        return $s;
    }
}

/*
yProfiler::start();

for ($i = 1; $i < 3; $i++){
    echo ($i)."\n";
    sleep(1);
}
echo yProfiler::getInstance();
*/
